using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using OrderingSystem.Core.Interfaces;
using OrderingSystem.Infrastructure.Data;
using OrderingSystem.Infrastructure.Services;
// 使用别名解决命名冲突
using InfraNotificationService = OrderingSystem.Infrastructure.Services.NotificationService;
using ApiNotificationService = OrderingSystem.API.Services.NotificationService;
using System.Text;
using OrderingSystem.API.Hubs;

var builder = WebApplication.CreateBuilder(args);

// 显式设置应用程序URL，只在8080端口运行，避免与前端冲突
builder.WebHost.UseUrls("http://localhost:8080");

// Add services to the container.
builder.Services.AddControllers();

// 配置日志
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();

// 添加CORS服务
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    });
});

// Configure database
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
    // 在开发环境中启用详细日志
    if (builder.Environment.IsDevelopment())
    {
        options.EnableSensitiveDataLogging()
               .EnableDetailedErrors()
               .LogTo(Console.WriteLine, LogLevel.Information);
    }
});

// 注册服务
builder.Services.AddScoped<IFileService, FileService>();
// 使用完全限定名称指定要使用的NotificationService实现
builder.Services.AddScoped<INotificationService, InfraNotificationService>();
builder.Services.AddScoped<IReviewService, ReviewService>();
builder.Services.AddScoped<IDishDiscussionService, DishDiscussionService>();
builder.Services.AddScoped<INewsService, NewsService>();
builder.Services.AddScoped<IFavoriteService, FavoriteService>();
builder.Services.AddScoped<IChatService, ChatService>();
builder.Services.AddScoped<IConfigService, ConfigService>();

// Configure JWT Authentication
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["JwtSettings:Issuer"],
        ValidAudience = builder.Configuration["JwtSettings:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JwtSettings:SecretKey"]))
    };
});

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "点餐系统API", Version = "v1" });
    
    // 添加JWT认证配置
    c.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        In = Microsoft.OpenApi.Models.ParameterLocation.Header,
        Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });
    
    c.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
    {
        {
            new Microsoft.OpenApi.Models.OpenApiSecurityScheme
            {
                Reference = new Microsoft.OpenApi.Models.OpenApiReference
                {
                    Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            Array.Empty<string>()
        }
    });
});

// 添加SignalR服务
builder.Services.AddSignalR();

var app = builder.Build();

// 初始化数据库
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    try
    {
        var context = services.GetRequiredService<ApplicationDbContext>();
        var logger = services.GetRequiredService<ILogger<Program>>();
        
        logger.LogInformation("开始初始化数据库...");
        
        // 验证数据库连接
        try {
            logger.LogInformation("正在验证数据库连接...");
            context.Database.OpenConnection();
            context.Database.CloseConnection();
            logger.LogInformation("数据库连接验证成功");
        }
        catch (Exception ex) {
            logger.LogError(ex, "数据库连接验证失败");
            throw;
        }
        
        // 输出数据库表信息
        logger.LogInformation("数据库表信息:");
        foreach (var entityType in context.Model.GetEntityTypes())
        {
            logger.LogInformation($"实体: {entityType.Name}, 表名: {entityType.GetTableName()}");
            foreach (var property in entityType.GetProperties())
            {
                logger.LogInformation($"  属性: {property.Name}, 列名: {property.GetColumnName()}");
            }
        }
        
        await DbInitializer.Initialize(context, logger);
        logger.LogInformation("数据库初始化完成");
    }
    catch (Exception ex)
    {
        var logger = services.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "初始化数据库时出错");
    }
}

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

// 使用路径基础前缀 - 这是一种更简单的方法来实现路由前缀
app.UsePathBase("/ssmjxtr8");

// 添加静态文件服务 - 确保在UsePathBase之后配置
app.UseStaticFiles();

app.UseCors("AllowAll");

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
// 配置SignalR Hub
app.MapHub<NotificationHub>("/hubs/notification");

app.Run();

// 修复可为空引用类型警告
record WeatherForecast(DateOnly Date, int TemperatureC, string Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
